//
//  HTClassPayManager.swift
//  QuitSmokingApp
//
//  Created by z on 2024/3/18.
//

import Foundation
import UIKit
import StoreKit

let var_HTClassPayManagerInstance = HTClassPayManager.var_default

class HTClassPayManager: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver{
 
    static var var_default: HTClassPayManager = HTClassPayManager()
    
#warning("var_password须与AppStore Connect匹配，var_state记得修改生产环境！！！！！")
    //须与AppStore Connect匹配
    private let var_password = "27b047287f114cf8a1f30b7856625527"
    //21008表示生产环境使用  21007表示测试环境使用
    private var var_state = 21007
    
    //沙盒验证地址
    private let var_receipt_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt"
    //生产环境验证地址
    private let var_receipt_itunes = "https://buy.itunes.apple.com/verifyReceipt"
    //是否请求所有产品
    private var var_isRequestAll = false
    //是否是恢复购买
    private var var_isRestore = false
    //所有产品回调
    var var_allProductsCallback: (([SKProduct])->())?
    //交易结果回调
    var var_payResultBlock: ((_ var_isSuccess: Bool, _ var_isCancel: Bool, _ var_msg: String, _ var_purchaseInfo: [String: Any]) ->())?
    
    deinit {
        SKPaymentQueue.default().remove(self)
    }
    
    //添加监听
    func ht_addTransactionObserver(){
        SKPaymentQueue.default().add(self)
    }
    
    //获取所有产品信息
    func ht_requestProducts(var_productIds: [String], var_callback: (([SKProduct])->())?) {
        if SKPaymentQueue.canMakePayments() == false {
            return
        }
        var_isRequestAll = true
        var_allProductsCallback = var_callback
        let var_set = Set<String>.init(var_productIds)
        let var_request = SKProductsRequest.init(productIdentifiers: var_set)
        var_request.delegate = self
        var_request.start()
    }

    //获取指定产品并发起付款
    func ht_requestProduct(var_productId: String, var_callback: ((_ var_isSuccess: Bool, _ var_isCancel: Bool, _ var_msg: String, _ var_purchaseInfo: [String: Any]) ->())?) {
        if SKPaymentQueue.canMakePayments() == false {
            return
        }
        
        var_isRequestAll = false
        var_payResultBlock = var_callback
        let var_set = Set<String>.init([var_productId])
        let var_request = SKProductsRequest.init(productIdentifiers: var_set)
        var_request.delegate = self
        var_request.start()
    }
    
    //恢复购买
    func ht_restore(var_callback: ((_ var_isSuccess: Bool, _ var_isCancel: Bool, _ var_msg: String, _ var_purchaseInfo: [String: Any]) ->())?){
        SKPaymentQueue.default().restoreCompletedTransactions()
        var_payResultBlock = var_callback
    }
    
    //获取产品回调
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        if response.products.count == 0 {
            print("productId没有对应的产品")
            return
        }
        
        if var_isRequestAll {
            //获取所有产品信息
            var_allProductsCallback?(response.products)
            return
        }
        
        //发起购买
        for var_pro in response.products {
            let var_payment = SKMutablePayment.init(product: var_pro)
            SKPaymentQueue.default().add(var_payment)
        }
    }
    
    //购买回调
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for var_tran in transactions {
            switch var_tran.transactionState {
            case .purchased://购买完成
                print("------>购买完成")
                var_isRestore = false
                ht_transactionSucceed(var_transaction: var_tran)
                break
            case.purchasing://商品添加进列表
                break
            case.restored://已经购买过该商品
                ht_transactionFailed(var_transaction: var_tran)
                break
            case.deferred://交易延迟
                ht_transactionFailed(var_transaction: var_tran)
                break
            case.failed://购买失败
                print("------>购买失败")
                ht_transactionFailed(var_transaction: var_tran)
                break
            default:
                ht_transactionFailed(var_transaction: var_tran)
                break
            }
        }
    }
    
    //恢复购买成功回调
    func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
        if queue.transactions.count != 0 {
            var_isRestore = true
            //校验订单
            let var_purchases = queue.transactions
            let var_shortPurchases = var_purchases.sorted(by: { $0.transactionDate! > $1.transactionDate!})
            if var_shortPurchases.count > 0 {
                //客户端验证
                ht_transactionSucceed(var_transaction: var_shortPurchases.first!)
            }else{
                //没有可恢复的购买项
                self.var_payResultBlock?(false, false, "No products have been purchased!", [:])
            }
        }else{
            //没有可恢复的购买项
            self.var_payResultBlock?(false, false, "No products have been purchased!", [:])
        }
    }
    
    //恢复购买失败回调
    func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: any Error) {
        //没有可恢复的购买项
        self.var_payResultBlock?(false, false, "No products have been purchased!", [:])
    }
    
    //交易成功处理
    func ht_transactionSucceed(var_transaction: SKPaymentTransaction){
        //获取交易凭证
        let var_recepitUrl = Bundle.main.appStoreReceiptURL
        let var_data = try! Data.init(contentsOf: var_recepitUrl!)
        if var_recepitUrl == nil {
            self.var_payResultBlock?(false, false, "No transaction voucher was obtained!", ["productId": var_transaction.payment.productIdentifier])
            print("交易凭证为空")
            return
        }
        
        //客户端验证
        ht_verify(var_data: var_data, var_transaction: var_transaction)
    }
    
    //交易失败处理
    func ht_transactionFailed(var_transaction: SKPaymentTransaction){
        if var_transaction.transactionState == .restored {
            SKPaymentQueue.default().finishTransaction(var_transaction)
            return
        }
        if ((var_transaction.error as! SKError).code == SKError.paymentCancelled){
            print("您取消了内购操作.");
            self.var_payResultBlock?(false, true, "", [:])
        } else {
            print("内购失败，原因：%\(String(describing: var_transaction.error?.localizedDescription))");
            self.var_payResultBlock?(false, false, "\(String(describing: var_transaction.error?.localizedDescription))", [:])
        }
        SKPaymentQueue.default().finishTransaction(var_transaction)
    }
    
    //客户端验证
    func ht_verify(var_data: Data, var_transaction: SKPaymentTransaction)  {
        let var_base64Str = var_data.base64EncodedString(options: .endLineWithLineFeed)
        let var_params = NSMutableDictionary()
        var_params["receipt-data"] = var_base64Str
        //须与AppStore Connect匹配
        var_params["password"] = var_password
        let var_body = try! JSONSerialization.data(withJSONObject: var_params, options: .prettyPrinted)
        var var_request = URLRequest.init(url: URL.init(string: var_state == 21008 ? var_receipt_itunes : var_receipt_sandbox)!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30)
        var_request.httpMethod = "POST"
        var_request.httpBody = var_body
        let var_session = URLSession.shared
        let var_task = var_session.dataTask(with: var_request) {[weak self] (var_data, var_response, var_error) in
            if var_data == nil {
                SKPaymentQueue.default().finishTransaction(var_transaction)
                return
            }
            let var_dict = try! JSONSerialization.jsonObject(with: var_data!, options: .mutableContainers) as! NSDictionary
//            print("------>购买结果，\(var_dict)")
            //关闭交易
            SKPaymentQueue.default().finishTransaction(var_transaction)
            let var_status = var_dict["status"] as! Int
            switch(var_status){
            case 0:
                //所有付款list
                let var_receipt = var_dict["latest_receipt_info"] as! Array<Any>
                //最新的一条付款
                let var_purchaseInfo = var_receipt.first as! [String: Any]
                //订阅信息
                let var_renewalInfo = var_dict["pending_renewal_info"] as! Array<Any>
                //最新的一条订阅
                let var_renewal = var_renewalInfo.first as! [String: Any]
                
                //存储内购信息
                var var_model = HTClassPurchaseInfoModel()
                var_model.var_productId = var_renewal["auto_renew_product_id"] as! String
                var_model.var_expiresDateMS = TimeInterval(Int(var_purchaseInfo["expires_date_ms"] as! String)!)
                HTClassStorage.ht_savePurchaseInfo(var_model)
                
                if self?.var_isRestore == true {
                    if var_model.var_isSubscribe == false {
                        self?.var_payResultBlock?(false, false, "No products have been purchased!", ["productId": var_purchaseInfo["purchase_id"] ?? "", "expiresDate": var_purchaseInfo["expires_date"] ?? ""])
                    }else{
                        self?.var_payResultBlock?(true, false, "Your subscription status has been restored!", ["productId": var_purchaseInfo["purchase_id"] ?? "", "expiresDate": var_purchaseInfo["expires_date"] ?? ""])
                    }
                }else{
                    self?.var_payResultBlock?(true, false, "Successful purchase!", ["productId": var_purchaseInfo["purchase_id"] ?? "", "expiresDate": var_purchaseInfo["expires_date"] ?? ""])
                }
                break
            case 21007:
                //以防生产环境使用了测试环境的验证地址，所以重新验证
                self?.var_state = 21007
                self?.ht_verify(var_data: var_data!, var_transaction: var_transaction)
                break
            default:
                self?.var_payResultBlock?(false, false, "Purchase failed, please try again later!", ["productId": var_transaction.payment.productIdentifier])
                break
            }
        }
        var_task.resume()
    }
}
